//
//  FirstTouchController.m
//  EMMApp
//
//  Created by 无常先生 on 2018/8/20.
//  Copyright © 2018年 YiXun. All rights reserved.
//

#import "FirstTouchController.h"
#import "UIView+Extension.h"
#import "firstTouchCell.h"
#import "FirstTouchHeaderView.h"
#import "FirstTouchFooterView.h"
#import "GetContactWayAPI.h"
#import "CustomerList.h"
#import "GetDictionaryList.h"
#import "GetDictionaryListApi.h"
#import "FirstTouchTypeModel.h"
#import <MJExtension.h>
#import "AddContactAPI.h"

@interface FirstTouchController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, weak) UITableView *tableView;

@property (nonatomic, strong) ContactWayModel *model;
@property (nonatomic, strong) NSArray *types;
@property (nonatomic, copy) NSString *nowDate;
@property (nonatomic, weak) UIButton *saveBtn;
@property (nonatomic, copy) NSString *selecType;

@property (nonatomic, weak) FirstTouchFooterView *footerView ;
@end

static NSString *const cellID = @"cellID";
@implementation FirstTouchController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatNavigationBar];
    [self prepareUI];
    [self reloadDataWithAPI];
    [self getFirstTouchType];
    [self getNowData];
}

- (void)prepareUI{
    
    UITableView *listView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    listView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    listView.delegate = self;
    listView.dataSource = self;
    listView.showsVerticalScrollIndicator = NO;
    listView.rowHeight = 65;
    listView.sectionHeaderHeight = 0;
    FirstTouchHeaderView *headerView = [FirstTouchHeaderView loadView];
    headerView.userModel = self.userModel;
    listView.tableHeaderView = headerView;
    
    [listView registerNib:[UINib nibWithNibName:NSStringFromClass([firstTouchCell class]) bundle:nil] forCellReuseIdentifier:cellID];
    [self.view addSubview:listView];
    self.tableView = listView;
    
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, listView.width, 80)];
    
    UIButton *saveBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 20, footerView.width - 20, 45)];
    saveBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    saveBtn.backgroundColor = [UIColor colorFromHexCode:@"#FB5A3B"];
    saveBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    saveBtn.layer.cornerRadius = 4;
    [saveBtn addTarget:self action:@selector(saveButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:saveBtn];
    self.saveBtn = saveBtn;
    
    listView.tableFooterView = footerView;
    
}

- (void)creatNavigationBar {
    
    self.title = @"首次接触信息";
    self.navigationController.navigationBar.translucent = YES;
    //返回按钮初始化
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setFrame:CGRectMake(0, 0, 54 ,44)];
    [backBtn addTarget:self
                action:@selector(NewbackToPreviousPage)
      forControlEvents:UIControlEventTouchUpInside];
    [backBtn setBackgroundColor:[UIColor clearColor]];
    [backBtn setImage:[UIImage imageNamed:@"ico_back"] forState:UIControlStateNormal];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    if (EMM_WIDTH <= 320) {
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    }else if (EMM_WIDTH > 375){
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    }else{
        backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    }
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
}


- (void)NewbackToPreviousPage {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - methods
- (void)saveButtonClick {

    AddContactAPI *api = [[AddContactAPI alloc]initWithTypeID:self.selecType date:self.nowDate note:self.footerView.nowNote customerId:self.userModel.customerId];
    [self showHudInWindow:@"更新中。。。"];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [self hideHud];
        AddContactAPI *result = (AddContactAPI *)request;
        NSDictionary *finishData = result.responseJSONObject[@"resData"];
        NSString *status = finishData[@"result"];
        if ([status isEqualToString:@"1"]) {
            [self showToast:@"更新成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.75 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else {
            [self showToast:finishData[@"errorMsg"]];
        }
    } failure:^(YTKBaseRequest *request) {
        [self hideHud];
        [self showToast:@"连接服务器失败，请检查网络！"];
    }];
}


#pragma mark - getData
- (void)reloadDataWithAPI {
    GetContactWayAPI *api = [[GetContactWayAPI alloc]initWthCustomerId:self.userModel.customerId];
    [self showHudInWindow:@"正在加载请稍等..."];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
         [self hideHud];
         GetContactWayAPI *result = (GetContactWayAPI *)request;
        if (result.resultData) {
             ContactWayModel *model = result.resultData;
             self.model = model;
            [self.tableView reloadData];
            if (model.ftContactContent1) {
                self.saveBtn.hidden = YES;
            }
            
        }else {
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:@"网络错误，请稍后再试。。"];
            }
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }

        }
        
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

- (void)getFirstTouchType {
    
    GetDictionaryListApi *api = [[GetDictionaryListApi alloc] initWithBusNum:@"01" busNumType:@"11"];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetDictionaryListApi *result = (GetDictionaryListApi *)request;
        NSDictionary *dict = result.responseJSONObject[@"resData"];
        self.types = [FirstTouchTypeModel mj_objectArrayWithKeyValuesArray:dict[@"rqBusNumList"]];
        
        if (!self.types.count) {
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
        }
        }
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
    }];
}

- (void)getNowData {
    NSString *path = [NSString stringWithFormat:@"%@/appapi/getServerTime", apiBaseUrl];
    [[AFHTTPSessionManager manager]GET:path parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dict = responseObject[@"resData"];
        NSString *date = dict[@"serverTime"];
        if (date.length > 11) {
          NSString *today = [date substringToIndex:10];
         self.nowDate = [NSString stringWithFormat:@"%@", today];
        }
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}


#pragma mark - delegate & dataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(self.model.ftContactWay.length){
        return 2;
    }else {
        return 1;
    }
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    firstTouchCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.types = self.types;
    cell.nowData = self.nowDate;
    [cell updataUIWithModel:self.model indxPath:indexPath];
    __weak typeof(self)weakSelf = self;
    cell.selectedTypeCallBack = ^(NSString *type) {
        weakSelf.selecType = type;
    } ;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    FirstTouchFooterView *footerView = [FirstTouchFooterView loadView];
    if (self.model.ftContactWay.length) {
        footerView.note = section == 0 ? self.model.ftContactContent : self.model.ftContactContent1;
    }else {
        footerView.note = self.model.ftContactContent1;
    }
    self.footerView = footerView;
    return footerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 90;
}

@end
